<?php

namespace app\common\model\business;

use think\Model;
use think\Env;

class Business extends Model
{
    // 指定数据表
    protected $table = 'pre_business';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    //追加数据表不存在的字段
    protected $append = [
        'mobile_text',
        'avatar_cdn',
        'region_text',
        'deal_text',
        'gender_text'
    ];

    //获取器
    public function getMobileTextAttr($value, $data)
    {
        return substr_replace($data['mobile'], '****', 3, 4);
    }

    // ????
    public function getAvatarCdnAttr($values, $data)
    {
        $cdn = config('site.url');
        $cdn = Env::get('site.url', $cdn);
        $avatar = $data['avatar'] ?? '';

        if (empty($avatar)) {
            $avatar = '/assets/img/avatar.png';
        }

        return $cdn . ltrim($avatar, '/');
    }

    public function getRegionTextAttr($value, $data)
    {
        $region_text = '';

        $province = model('Region')->where(['code' => $data['province']])->value('name');
        $city = model('Region')->where(['code' => $data['city']])->value('name');
        $district = model('Region')->where(['code' => $data['district']])->value('name');

        if ($province) {
            $region_text = $province;
        }

        if ($city) {
            $region_text .= '-' . $city;
        }

        if ($district) {
            $region_text .= '-' . $district;
        }

        return $region_text;
    }

    public function source(){
        return $this->belongsTo('app\common\model\business\Source', 'sourceid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getDealTextAttr($value,$data){
        $list = [0 => '未成交', 1 => '已成交'];
        return $list[$data['deal']];
    }

    public function getGenderTextAttr($value, $data)
    {
        $genderList = [0 => '保密', 1 => '男', 2 => '女'];

        return $genderList[$data['gender']];
    }
}